﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Controls;
using VAdvantage.Classes;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.Grids;
using System.Data.SqlClient;
using VAdvantage.DataBase;
using System.Threading;
using System.Text;
using System.ComponentModel;
using System.IO;
using VAdvantage.ProcessEngine;

namespace VAdvantage.Process
{
    public partial class ProcessParameter : ChildWindow
    {
        private ProcessInfo pi;

        public Ctx ctx = Utility.Envs.GetContext();

        private int windowNo = 0;

        List<GridField> lstFields = new List<GridField>(30);
        List<IControl> lstVEditors = new List<IControl>();
        List<GridField> lstFields2 = new List<GridField>(30);
        List<IControl> lstVEditors2 = new List<IControl>();
        //Grid tblpnlS = new Grid();

        private bool _isOK = false;

        ProcessCtl process = null;

        /**	Parenr				*/
        ASyncProcess _parent;

        public ASyncProcess AsyncProcessInfo
        {
            get { return _parent; }
            set { _parent = value; }
        }

        //Grid tblpnlS;

        //Progress obj = new Progress();

        public ProcessParameter(ProcessInfo _pi, int _windowNo)
        {
            //tblpnlS.Width = 250;
            //tblpnlS.Height = 100;
            //tblpnlS.HorizontalAlignment = HorizontalAlignment.Left;
            //tblpnlS.VerticalAlignment = VerticalAlignment.Top;


            pi = _pi;
            windowNo = _windowNo;
            //this.Height = formHeight;
            InitializeComponent();
            //tblpnlS.ShowGridLines = true;
        }

        private int m_sLine = 0;
        private int fixedWidth = 0;
        VComboBox cmbSelected = null;


        /// <summary>
        /// Creates the field on the form
        /// </summary>
        /// <param name="dr">datarow</param>
        private void CreateField(DataRow dr)
        {
            GridFieldVO fvo = GridFieldVO.CreateParameter(Utility.Envs.GetContext(), windowNo, dr);
            GridField fo = new GridField(fvo);
            lstFields.Add(fo);
            Object defaultObject = fo.GetDefault();
            bool created = false;

            Deployment.Current.Dispatcher.BeginInvoke
            (delegate
            {

                IControl ctrl = null;
                ctrl = VControlFactory.GetControl(null, fo, false, false, false);

              
                fo.SetValue(defaultObject, true);

                VLabel label = VControlFactory.GetLabel(fo);


                if (ctrl is VComboBox)
                {
                    cmbSelected = (VComboBox)ctrl;
                    cmbSelected.SelectionChanged += new SelectionChangedEventHandler(cmbSelected_SelectionChanged);
                    //ctrl.VetoableChangeListener += new System.EventHandler(this.hello);
                }

                RowDefinition row = new RowDefinition();
                row.Height = new GridLength(0, GridUnitType.Auto);
                row.MinHeight = 30;
                tblpnlS.RowDefinitions.Add(row);


                if (m_sLine == 0)
                {
                    ColumnDefinition column = new ColumnDefinition();
                    column.Width = new GridLength(30, GridUnitType.Star);
                    tblpnlS.ColumnDefinitions.Add(column);

                    column = new ColumnDefinition();
                    column.Width = new GridLength(70, GridUnitType.Star);
                    tblpnlS.ColumnDefinitions.Add(column);

                }

                if (label != null)
                {
                    label.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    label.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    label.Margin = new Thickness(0, 0, 5, 0);

                    Grid.SetColumn(label, 0);
                    Grid.SetRow(label, m_sLine);
                    tblpnlS.Children.Add(label);
                }
                if (ctrl != null)
                {

                    Control c = (Control)ctrl;
                    Grid.SetColumn(c, 1);
                    Grid.SetRow(c, m_sLine);
                    tblpnlS.Children.Add(c);
                    c.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    c.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    c.Margin = new Thickness(0, 0, 5, 0);
                    c.Height = 23;
                    c.Width = 270;
                    lstVEditors.Add(ctrl);
                    ctrl.SetValue(defaultObject);
                }


                if (fvo.isRange)
                {
                    row = new RowDefinition();
                    row.Height = new GridLength(0, GridUnitType.Auto);
                    row.MinHeight = 30;
                    tblpnlS.RowDefinitions.Add(row);

                    GridFieldVO fvo2 = GridFieldVO.CreateParameter(fvo);
                    GridField fo2 = new GridField(fvo2);
                    lstFields2.Add(fo2);

                    IControl ctrl2 = null;
                    ctrl2 = VControlFactory.GetControl(null, fo2, false, false, false);

                    Object defaultObject2 = fo2.GetDefault();
                    fo2.SetValue(defaultObject2, true);

                    m_sLine++;

                    Control c2 = (Control)ctrl2;
                    Grid.SetRow(c2, m_sLine);
                    Grid.SetColumn(c2, 1);

                    c2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    c2.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    c2.Margin = new Thickness(0, 0, 5, 0);
                    c2.Height = 23;
                    c2.Width = 270;

                    tblpnlS.Children.Add(c2);
                    lstVEditors2.Add(ctrl2);

                    ctrl2.SetValue(defaultObject2);
                }
                else
                {
                    lstVEditors2.Add(null);
                    lstFields2.Add(null);
                }

                m_sLine++;
                //tblpnlS.Height = (50 * m_sLine);

                created = true;

            });


            while (!created)
            {
                Thread.Sleep(0);
            }

            created = false;
        }


        void cmbSelected_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //String value = ((IControl)sender).GetValue().ToString();// evt.getNewValue() == null ? "" : evt.getNewValue().toString();
            String value = ((IControl)sender).GetValue() == null ? "" : ((IControl)sender).GetValue().ToString();
           // Utility.Envs.GetCtx().SetContext(windowNo, ((Control)sender).Name, value);
            Utility.Envs.GetCtx().SetContext(windowNo, ((IControl)sender).GetName(), value);
        }


        bool hasFields = false;
        private DataSet dsFields = null;
        private Double formHeight = 0;

        internal bool InitDialog()
        {
            string strSql = "";
            SqlParameter[] param;
            if (Utility.Envs.IsBaseLanguage(ctx, ""))//    GlobalVariable.IsBaseLanguage())
            {
                param = new SqlParameter[1];
                param[0] = new SqlParameter("@processid", pi.GetAD_Process_ID());
                strSql = "SELECT p.Name, p.Description, p.Help, "
                    + "p.AD_Reference_ID, p.AD_Process_Para_ID, "
                    + "p.FieldLength, p.IsMandatory IsMandatoryUI, p.IsRange, p.ColumnName, "
                    + "p.DefaultValue, p.DefaultValue2, p.VFormat, p.ValueMin, p.ValueMax, "
                    + "p.SeqNo, p.AD_Reference_Value_ID, vr.Code AS ValidationCode "
                    + "FROM AD_Process_Para p"
                    + " LEFT OUTER JOIN AD_Val_Rule vr ON (p.AD_Val_Rule_ID=vr.AD_Val_Rule_ID) "
                    + "WHERE p.AD_Process_ID=@processid"		//	1
                    + " AND p.IsActive='Y' "
                    + "ORDER BY SeqNo";
            }
            else
            {
                param = new SqlParameter[1];
                param[0] = new SqlParameter("@processid", pi.GetAD_Process_ID());
                strSql = "SELECT t.Name, t.Description, t.Help, "
                    + "p.AD_Reference_ID, p.AD_Process_Para_ID, "
                    + "p.FieldLength, p.IsMandatory IsMandatoryUI, p.IsRange, p.ColumnName, "
                    + "p.DefaultValue, p.DefaultValue2, p.VFormat, p.ValueMin, p.ValueMax, "
                    + "p.SeqNo, p.AD_Reference_Value_ID, vr.Code AS ValidationCode "
                    + "FROM AD_Process_Para p"
                    + " INNER JOIN AD_Process_Para_Trl t ON (p.AD_Process_Para_ID=t.AD_Process_Para_ID)"
                    + " LEFT OUTER JOIN AD_Val_Rule vr ON (p.AD_Val_Rule_ID=vr.AD_Val_Rule_ID) "
                    + "WHERE p.AD_Process_ID=@processid"		//	1
                    + " AND t.AD_Language='" + Utility.Envs.GetAD_Language(ctx) + "'"
                    + " AND p.IsActive='Y' "
                    + "ORDER BY SeqNo";
            }
            DataSet ds = DB.ExecuteDataset(strSql, param, null);

            if (ds.Tables[0].Rows.Count > 0)
            {
                hasFields = true;
                dsFields = ds;
            }

            formHeight = (ds.Tables[0].Rows.Count + 70);
            return hasFields;
        }

        internal bool IsOK()
        {
            return _isOK;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            //check mandatory status and give appropriate message
            Utility.Envs.SetBusyIndicator(true);

            StringBuilder sb = new StringBuilder("");
            int iSize = lstFields.Count();
            for (int i = 0; i <= iSize - 1; i++)
            {
                GridField fo = (GridField)lstFields[i];
                if (fo.IsMandatory(true))   //check if mandatory
                {
                    //fetch data from fields
                    IControl vco = lstVEditors[i];
                    Object objData = vco.GetValue();
                    if (objData == null || objData.ToString().Length == 0)
                    {
                        if (sb.ToString().Length > 0)
                            sb.Append(", ");
                        sb.Append(fo.GetHeader());
                    }
                    else
                        fo.SetError(false);


                    IControl editor2 = null;
                    if (lstVEditors2.Count > 0)
                        editor2 = lstVEditors2[i];

                    if (editor2 != null)
                    {
                        Object data2 = vco.GetValue();
                        GridField fo2 = (GridField)lstFields2[i];
                        if (data2 == null || data2.ToString().Length == 0)
                        {
                            fo2.SetError(true);
                            if (sb.Length > 0)
                                sb.Append(", ");
                            sb.Append(fo.GetHeader());
                        }
                        else
                            fo2.SetError(false);
                    }   //range field
                }   //mandatory
            }//field loop


            if (sb.ToString().Length != 0)  //if length is 0, then  show message
            {
                ShowMessage.Error("FillMandatory", true, sb.ToString());
                return;
                //MessageBox.Show("Fill mandatory fileds");
                //return false;
            }


            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
                {
                    for (int i = 0; i < lstFields.Count(); i++)
                    {
                        //create parameter

                        MPInstancePara para = null;
                        GridField fo = null;


                        para = new MPInstancePara(ctx, pi.GetAD_PInstance_ID(), i);


                        IControl editor = lstVEditors[i];

                        IControl editor2 = null;
                        if (lstVEditors2.Count > 0)
                            editor2 = lstVEditors2[i];
                        Object objResult = null;
                        Object objResult2 = null;

                        bool doMove = false;
                        Dispatcher.BeginInvoke(delegate
                        {
                            objResult = editor.GetValue();

                            if (editor2 != null)
                            {

                                objResult2 = editor2.GetValue();

                            }

                            doMove = true;
                        });

                        while (!doMove)
                            Thread.Sleep(10);

                        doMove = false;


                        //Don't save null values
                        if (objResult == null && objResult2 == null)
                            continue;

                        if (objResult == DBNull.Value)
                            continue;


                        bool b = System.Windows.Deployment.Current.Dispatcher.CheckAccess();

                        //MPInstancePara para = null;
                        //GridField fo = null;


                        para = new MPInstancePara(ctx, pi.GetAD_PInstance_ID(), i);


                        fo = (GridField)lstFields[i];
                        para.SetParameterName(fo.GetColumnName());


                        //while(para == null)
                        //{
                        //    Thread.Sleep(10);
                        //}

                        //date
                        if (objResult is DateTime || objResult2 is DateTime)
                        //if (objResult.GetType() == typeof(DateTime) && objResult2.GetType() == typeof(DateTime))
                        {
                            para.SetP_Date((DateTime?)objResult);
                            if (objResult2 == DBNull.Value)
                            {
                                objResult2 = null;
                            }
                            if (editor2 != null && objResult2 != null)
                            {

                                para.SetP_Date_To((DateTime)objResult2);
                            }

                        }
                        else if (objResult.GetType() == typeof(int))
                        {
                            if (objResult != null)
                            {
                                int ii = (int)objResult;
                                para.SetP_Number(ii);
                            }
                            if (editor2 != null && objResult2 != null)
                            {
                                int ii = (int)objResult2;
                                para.SetP_Number_To(ii);
                            }
                        }
                        else if (objResult.GetType() == typeof(decimal))
                        {
                            para.SetP_Number((decimal)objResult);
                            if (editor2 != null && objResult2 != null)
                                para.SetP_Number_To((decimal)objResult2);
                        }
                        else if (objResult.GetType() == typeof(bool))
                        {
                            bool bln = (bool)objResult;
                            String value = bln ? "Y" : "N";
                            para.SetP_String(value);

                        }
                        else
                        {
                            if (objResult != null)
                                para.SetP_String(objResult.ToString());
                            if (editor2 != null && objResult2 != null)
                                para.SetP_String_To(objResult2.ToString());
                        }

                        Dispatcher.BeginInvoke(delegate
                        {
                            para.SetInfo(editor.GetText());
                            if (editor2 != null)
                                para.SetInfo_To(editor2.GetText());

                            doMove = true;
                        });

                        while (!doMove)
                            Thread.Sleep(10);

                        doMove = false;
                        //info not written

                        bool save = para.Save();
                        if (save)
                        {
                            //saveParameter = true;


                        }
                    }

                    _isOK = true;

                    Dispatcher.BeginInvoke(delegate
                    {
                        this.DialogResult = true;
                    });

                    //process = new ProcessCtl(_parent, pi, null);
                    //process.Run();

                };

            bgw.RunWorkerAsync();

        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            Utility.Envs.SetBusyIndicator(false);
            this.DialogResult = false;
        }

        private void ChildWindow_Closed(object sender, EventArgs e)
        {

        }

        private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Collapsed;
            Envs.SetBusyIndicator(true);
            ThreadPool.QueueUserWorkItem(delegate
            {
                int ss = 1;
                foreach (DataRow dr in dsFields.Tables[0].Rows)
                {
                    CreateField(dr);
                    ss++;
                }

                Dispatcher.BeginInvoke(delegate
                {
                    Envs.SetBusyIndicator(false);
                    this.Visibility = System.Windows.Visibility.Visible;
                });
            });
        }

        bool saveParameter = false;
        /// <summary>
        /// Fetches the values entered into textbox and updates into DB
        /// </summary>
        protected void SaveParameter()
        {



            //return true;
        }


        private void Unlock()
        {
            String summary = pi.GetSummary();
            if (summary != null && summary.IndexOf("@") != -1)
                pi.SetSummary(Utility.Msg.ParseTranslation(Utility.Envs.GetContext(), summary));
            if (_parent != null)
            {
                if (!System.Windows.Deployment.Current.Dispatcher.CheckAccess())
                {
                    _parent.UnlockUI(pi);
                }
                else
                {
                    Thread t = new Thread(delegate() { _parent.UnlockUI(pi); });
                    t.CurrentCulture = Utility.Envs.GetLanguage(Utility.Envs.GetContext()).GetCulture(Utility.Envs.GetLoginLanguage(Utility.Envs.GetContext()).GetAD_Language());
                    t.CurrentUICulture = Utility.Envs.GetLanguage(Utility.Envs.GetContext()).GetCulture(Utility.Envs.GetLoginLanguage(Utility.Envs.GetContext()).GetAD_Language());
                    t.Start();
                }
            }
            //return _pi.GetSummary();
        }
    }
}
